/************************************************************************************************
 * test examples of 100 interesting program in C
 * test 008.c
 * Arrangement (5 books  to 3 persons)
 ***********************************************************************************************/

#include <stdio.h>

#define BOOK 5
#define PERSON 3

/*
 *
 */

int print(char* person)
{
    int i;
    for (i = 0; i < PERSON; i++)
        printf("%c", person[i]);
    printf("\n");
}

int main()
{
    char book[BOOK] = {'A', 'B', 'C', 'D', 'E'};
    int book_tag[BOOK] = {0};
    char person[PERSON] = {' ', ' ', ' '};

    int cur = 0;
    int count = 0;
    while (1)
    {
        //printf("%d->", cur);
        //print(person);
        if (cur == -1)
            break;
        if (cur == PERSON)
        {
            print(person);
            count++;
            cur--;
            //printf("backtrace\n");
            continue;
        }
        // find next to fill
        int i;
        if (person[cur] == ' ') i = 0;
        else i = person[cur]-'A'+1;
        for (; i < BOOK; i++)
            if (book_tag[i] == 0)
                break;
        if (i < BOOK)
        {
            book_tag[person[cur]-'A'] = 0;
            book_tag[i] = 1;
            person[cur] = book[i];
            cur++;
        }
        else
        {
            book_tag[person[cur]-'A'] = 0;
            person[cur] = ' ';
            cur--;
            //printf("backtrace\n");
        }
    }
    printf("Total %d kinds of arrangements.\n", count);
}

